const Router = require('koa-router')
const { check, catchError, generateOk } = require('../../lib/check')
const { searchAccountById, searchAccount } = require('../../model/accounts')
const { editBug, getAllBugs, searchBug } = require('../../model/bug')

let bug = new Router()

bug.post('/changeStatus', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!data.id, 'Params_Lost')
    // check(!!data.lable, 'Params_Lost')
    // check(data.state !== undefined, 'Params_Lost')
    const findBug = searchBug(data.id)
    check(findBug, 'Not_Bug')
    editBug({ ...findBug, status: findBug.status === 0 ? 1 : 0 })
    ctx.body = generateOk({ ...findBug, status: findBug.status === 0 ? 1 : 0 })
  } catch (e) {
    catchError(e, ctx)
  }
})

bug.post('/get', async (ctx) => {
  try {
    const data = ctx.request.body
    const bugs = getAllBugs()
    let newBugs = bugs

    if (data.create_Ts === 'descend') {
      newBugs = newBugs.sort((a, b) => Number(b.create_Ts) - Number(a.create_Ts))
    } else {
      newBugs = newBugs.sort((a, b) => Number(a.create_Ts) - Number(b.create_Ts))
    }
    if (!!data.userId) {
      const findAccount = searchAccountById(data.userId)
      check(findAccount, 'No_Such_Account')
      newBugs = newBugs.filter(item => item.userId === data.userId)
    }
    if (data.status !== undefined) {
      newBugs = newBugs.filter((item) => item.status === data.status)
    }
    if (data.content !== undefined) {
      newBugs = newBugs.filter((item) => item.content.includes(data.content))
    }
    const start = data.offset === undefined ? 0 : data.offset
    const size = data.limit === undefined ? 7 : data.limit
    const resData = newBugs.slice(start, start + size)
    ctx.body = generateOk({ data: resData, total: newBugs.length, length: resData.length })
  } catch (e) {
    catchError(e, ctx)
  }
})


module.exports = bug